package com.krmes.mes.photo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.krmes.mes.R;
import com.krmes.mes.app.AppContext;
import com.krmes.mes.base.BaseActivity;
import com.krmes.mes.photo.util.Bimp;
import com.krmes.mes.photo.util.ImageItem;
import com.krmes.mes.photo.util.PublicWay;
import com.krmes.mes.photo.util.Res;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Date;
import java.text.SimpleDateFormat;

import cz.msebera.android.httpclient.Header;


/**
 * 首页面activity
 *
 * @author king
 * @QQ:595163260
 * @version 2014年10月18日  下午11:48:34
 */
public class ImageUpActivity extends BaseActivity {

	private GridView noScrollgridview;
	private GridAdapter adapter;
	private View parentView;
	private PopupWindow pop = null;
	private LinearLayout ll_popup;
	public static Bitmap bimap ;
	RequestParams params;
	public  TextView comment;
	public TextView upload ;
	private String pathTakePhoto;
	private Uri imageUri;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Res.init(this);
		bimap = BitmapFactory.decodeResource(
				getResources(),
				R.drawable.icon_addpic_unfocused);
		PublicWay.activityList.add(this);
		parentView = getLayoutInflater().inflate(R.layout.activity_selectimg, null);
		setContentView(parentView);
		upload = (TextView) this.findViewById(R.id.activity_selectimg_send);
		params = new RequestParams();
		upload.setOnClickListener(this);
		params = (RequestParams)getIntent().getSerializableExtra("params");
		comment = (TextView) this.findViewById(R.id.et_up_comment);
		Init();
	}

	public void Init() {
		
		pop = new PopupWindow(ImageUpActivity.this);
		
		View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);

		ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
		
		pop.setWidth(LayoutParams.MATCH_PARENT);
		pop.setHeight(LayoutParams.WRAP_CONTENT);
		pop.setBackgroundDrawable(new BitmapDrawable());
		pop.setFocusable(true);
		pop.setOutsideTouchable(true);
		pop.setContentView(view);
		
		RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
		Button bt1 = (Button) view
				.findViewById(R.id.item_popupwindows_camera);
		Button bt2 = (Button) view
				.findViewById(R.id.item_popupwindows_Photo);
		Button bt3 = (Button) view
				.findViewById(R.id.item_popupwindows_cancel);
		parent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
		bt1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				photo();
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
		bt2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(ImageUpActivity.this,
						AlbumActivity.class);
                intent.putExtra("params",params);
				startActivity(intent);
				overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
				pop.dismiss();
				ll_popup.clearAnimation();
				finish();
			}
		});
		bt3.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
		
		noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		adapter.update();
		noScrollgridview.setAdapter(adapter);
		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == Bimp.tempSelectBitmap.size()) {
					Log.i("ddddddd", "----------");
					ll_popup.startAnimation(AnimationUtils.loadAnimation(ImageUpActivity.this, R.anim.activity_translate_in));
					pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
				} else {
					Intent intent = new Intent(ImageUpActivity.this,
							GalleryActivity.class);
					intent.putExtra("position", "1");
					intent.putExtra("ID", arg2);
                    intent.putExtra("params",params);
					startActivity(intent);
					finish();
				}
			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()){
			case R.id.activity_selectimg_send:
				if (upload.isEnabled() ==false	){AppContext.showToast("图片正在上传!");	}
				if (Bimp.tempSelectBitmap.size() >0){
					upload.setEnabled(false);
					//Toast.makeText(v.getContext()	,"上传待开发",Toast.LENGTH_LONG);
					String _comment = comment.getText().toString().trim();
					params.put("comment",_comment);//comment
//					String picpath ="";
//					if (Bimp.tempSelectBitmap.size() > 0) {
//						for(int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
////图片路径
//							if(i != Bimp.tempSelectBitmap.size() - 1) {
//								picpath = (Bimp.tempSelectBitmap.get(i).getImagePath() + "");
//							} else {
//								picpath = Bimp.tempSelectBitmap.get(i).getImagePath();
//							}
//							try {
//								params.put("img", new File(picpath));
//							} catch (FileNotFoundException e) {
//// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
//						}
//					}

//					for (ImageItem i:Bimp.tempSelectBitmap
//							) {
//						try {
//							//params.put("",new File(i.getImagePath()),"");
//							params.put(".jpg",new File(i.getImagePath()));
//							Log.i("eeeeeeeeeee", i.getImagePath());
//						} catch (FileNotFoundException e) {
//							e.printStackTrace();
//						}
//					}

					File[] files = new File[Bimp.tempSelectBitmap.size()];
					int a =0 ;
					for (ImageItem i:Bimp.tempSelectBitmap
							) {
							files[a] =  new File(i.getImagePath());
							a++;
							//params.put(".jpg",new File(i.getImagePath()));
					}
					try {
						//params.put("jpg",files,"file","1111111");
						params.put("jpg",files);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}

					//params.put(".jpg",Bimp.tempSelectBitmap.get(0));
					ServerApi.uploadFile2(params, new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
							String strurl =  new String(responseBody);
							if (strurl.length()>0) {
								AppContext.showToast("图片上传成功!");

								finish();
							}else {
								AppContext.showToast("图片上传失败");
								upload.setEnabled(true);
							}
						}
						@Override
						public void onFailure(int pInt, Header[] pArrayOfHeader, byte[] responseBody, Throwable pThrowable){
							AppContext.showToast("图片上传失败");
							upload.setEnabled(true);
						}
						@Override
						public void onProgress(long bytesWritten, long totalSize) {
							//showWaitDialog("正在上传图片");
						}
					});
				}else{
					//Toast.makeText(v.getContext()	,"先添加图片",Toast.LENGTH_LONG);
					AppContext.showToast("先添加图片");
					upload.setEnabled(true);
				}
				break;
		}
	}

	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private int selectedPosition = -1;
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			if(Bimp.tempSelectBitmap.size() == PublicWay.num){
				return PublicWay.num;
			}
			return (Bimp.tempSelectBitmap.size() + 1);
		}

		public Object getItem(int arg0) {
			return null;
		}

		public long getItemId(int arg0) {
			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.item_published_grida,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position ==Bimp.tempSelectBitmap.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == PublicWay.num) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap());
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					adapter.notifyDataSetChanged();
					break;
				}
				super.handleMessage(msg);
			}
		};

		public void loading() {
			new Thread(new Runnable() {
				public void run() {
					while (true) {
						if (Bimp.max == Bimp.tempSelectBitmap.size()) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							break;
						} else {
							Bimp.max += 1;
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
						}
					}
				}
			}).start();
		}
	}

	public String getString(String s) {
		String path = null;
		if (s == null)
			return "";
		for (int i = s.length() - 1; i > 0; i++) {
			s.charAt(i);
		}
		return path;
	}

	protected void onRestart() {
		adapter.update();
		super.onRestart();
	}

	private static final int TAKE_PICTURE = 0x000001;

	public void photo() {
//		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//		startActivityForResult(openCameraIntent, TAKE_PICTURE);
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date(System.currentTimeMillis());
		String filename = format.format(date);
		File outputImage = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), filename+".jpg");
		this.pathTakePhoto = outputImage.toString();
		try {
			if (outputImage.exists()) {
				outputImage.delete();
			}
			outputImage.createNewFile();
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.imageUri = Uri.fromFile(outputImage);
		Intent intentPhoto = new Intent("android.media.action.IMAGE_CAPTURE");
		intentPhoto.putExtra("output", this.imageUri);
		startActivityForResult(intentPhoto, TAKE_PICTURE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(imageUri, "image/*");
			intent.putExtra("scale", true);
			intent.putExtra("output", imageUri);
			Intent intentBc = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
			intentBc.setData(imageUri);
			sendBroadcast(intentBc);
			if (Bimp.tempSelectBitmap.size() < PublicWay.num && resultCode == RESULT_OK) {

//				SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
//				Date date = new Date(System.currentTimeMillis());
//				String filename = format.format(date);
//				Bitmap bm = (Bitmap) data.getExtras().get("data");
//				String fpath =  FileUtils.saveBitmap(bm, filename,this);

				BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
				bmpFactoryOptions.inJustDecodeBounds = true;
				Bitmap bm = BitmapFactory.decodeFile(pathTakePhoto, bmpFactoryOptions);
				String fpath =  pathTakePhoto;

				ImageItem takePhoto = new ImageItem();
				takePhoto.setBitmap(bm);
				takePhoto.setImagePath(fpath);
				Bimp.tempSelectBitmap.add(takePhoto);
			}
			break;
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			for(int i = 0; i< PublicWay.activityList.size(); i++){
				if (null != PublicWay.activityList.get(i)) {
					PublicWay.activityList.get(i).finish();
				}
			}
			finish();
			//System.exit(0);
		}
		return true;
	}

}

